package comm.SocketUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.*;

/**
 * @className: ServerThread
 * @description: 服务端线程.服务端处理实现
 * @date: 2022/6/8
 **/
public class ServerThread extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(ServerThread.class);


    public static Socket socket = null;
    //讲接收到的数据体（设备号或者消息ID）用逗号分割开，并且也会存很多垃圾数据，例如客户端连接之后默认发送的connection
    public static Set<String> split;
    //设备号对应的多个客户端


    public ServerThread(Socket socket) {
        try {
            ServerThread.socket = socket;
            split = new HashSet<>();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    @Override
    public void run() {
        //System.out.print("---11111----");
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //System.out.print("---222222----");
            while (true) {
                //读取从客户端传来的信息
                String readData = bufferedReader.readLine();

                //System.out.print("---thread in----内容：" + readData + "---");
                if (!Objects.equals(readData, "") && readData != null) {
                    split.addAll(Arrays.asList(readData.split(",")));
                    SocketMapClass.SocketMap.put(socket, split);
                    logger.info("--客户端连接总数--" + SocketMapClass.SocketMap.size() + ",已向map中添加客服端，ip--"+socket.getInetAddress()+"：" + socket.getPort());
//                } else {
//                    if (SocketMapClass.SocketMap.containsKey(socket)) {
//                        SocketMapClass.SocketMap.remove(socket, split);
//                        logger.info("移除客户端连接：" + socket.getInetAddress() + ":" + socket.getPort());
//                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}